<?php
// $Id: ntuts_question.admin.inc,v 1.4.2.3 2010/09/24 10:15:11 goba Exp $

/**
 * @file
 * Admin page callbacks for the ntuts_question module.
 */

function ntuts_question_setting(&$form_state) {
  $form = array();

  $form['ntuts_question_node_types'] = array(
    '#type' => 'fieldset',
    '#title' => t('Node types'),
    '#description' => t('Set the node types you want to activate ntuts_question on.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $array = array_keys(node_get_types('names'));

  for ($i = 0; $i < sizeof($array); $i++) {

    $form['ntuts_question_node_types']['ntuts_question_types'][$array[$i]] = array(
      '#type' => 'fieldset',
      '#title' => t($array[$i]),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );

    $form['ntuts_question_node_types']['ntuts_question_types'][$array[$i]]['ntuts_question_'. $array[$i] .'_enabled'] = array(
      '#type' => 'radios',
      '#title' => t('Enable ntuts_question for this type'),
      '#default_value' => variable_get('ntuts_question_'. $array[$i] .'_enabled', '1'),
      '#options' => array( t('Yes'), t('No')),
    );

  }
  return system_settings_form($form);
}


/**
 * Form builder; Builds the question overview form for the admin.
 *
 * @return
 *   The form structure.
 * @ingroup forms
 * @see ntuts_question_list_question_validate()
 * @see ntuts_question_list_question_submit()
 * @see theme_ntuts_question_list_question()
 */
function ntuts_question_list_question() {
  // build an 'Update options' form
  $form['options'] = array(
    '#type' => 'fieldset', '#title' => t('Update options'),
    '#prefix' => '<div class="container-inline">', '#suffix' => '</div>'
  );
  $options = array(    
      'unpublish' => 'Unpublish the selected questions',
      'publish' => 'Publish the selected questions',
      'delete' => 'Delete the selected questions',
  );
  $form['options']['operation'] = array('#type' => 'select', '#options' => $options, '#default_value' => 'unpublish');
  $form['options']['submit'] = array('#type' => 'submit', '#value' => t('Update'));

  // load the questions that we want to display
  $form['header'] = array('#type' => 'value', '#value' => array(
    theme('table_select_header_cell'),
    array('data' => t('Author'), 'field' => 'name'),
    array('data' => t('Posted in'), 'field' => 'node_title'),
    array('data' => t('Time'), 'field' => 'timestamp', 'sort' => 'desc'),
    array('data' => t('Status'), 'field' => 'status'),
    array('data' => t('Operations'))
  ));
  $result = pager_query('SELECT q.timestamp, q.status, q.qid, u.name, q.nid, n.title as node_title FROM {ntuts_question} q INNER JOIN {users} u ON u.uid = q.uid INNER JOIN {node} n ON n.nid = q.nid '. tablesort_sql($form['header']['#value']), 15, 0, NULL);

  // build a table listing the appropriate questions
  $destination = drupal_get_destination();
  while ($question = db_fetch_object($result)) {
    $questions[$question->qid] = '';
    $form['username'][$question->qid] = array('#value' => theme('username', $question));
    $form['node_title'][$question->qid] = array('#value' => l($question->node_title, 'node/'. $question->nid));
    $form['timestamp'][$question->qid] = array('#value' => format_date($question->timestamp, 'small'));
    $form['status'][$question->qid] = array('#value' => $question->status ? t('Published') : t('Not Published'));
    $form['operations'][$question->qid] = array('#value' => l(t('edit'), 'admin/content/ntuts_question/question/edit/'. $question->qid, array('query' => $destination)));
  }
  $form['questions'] = array('#type' => 'checkboxes', '#options' => isset($questions) ? $questions: array());
  $form['pager'] = array('#value' => theme('pager', NULL, 15, 0));
  return $form;
}

/**
 * Validate ntuts_question_list_question form submissions.
 *
 * We can't execute any 'Update options' if no questions were selected.
 */
function ntuts_question_list_question_validate($form, &$form_state) {
  $form_state['values']['questions'] = array_diff($form_state['values']['questions'], array(0));
  if (count($form_state['values']['questions']) == 0) {
    form_set_error('', t('Please select one or more questions to perform the update on.'));
  }
}

/**
 * Process ntuts_question_list_question form submissions.
 *
 * Execute the chosen 'Update option' on the selected questions, such as
 * publishing, unpublishing or deleting.
 */
function ntuts_question_list_question_submit($form, &$form_state) {
  $operations = array(
      'unpublish' => 'Unpublish the selected questions',
      'publish' => 'Publish the selected questions',
      'delete' => 'Delete the selected questions',
  );
  if (!empty($operations[$form_state['values']['operation']])) {
    $query = '';
    switch ($form_state['values']['operation']) {
      case 'unpublish':
        $query = 'UPDATE {ntuts_question} SET status = 0 WHERE qid = %d';
        break;
      case 'publish':
        $query = 'UPDATE {ntuts_question} SET status = 1 WHERE qid = %d';
        break;
      case 'delete':
        $query = 'DELETE FROM {ntuts_question} WHERE qid = %d';
        break;
      default:
        break;
    }
    // extract the appropriate database query operation
    if(!empty($query)) {

      foreach ($form_state['values']['questions'] as $qid => $value) {
        if ($value) {
          // perform the update action, then refresh node statistics
          db_query($query, $qid);
        }
      }
      drupal_set_message(t('The update has been performed.'));
    }    
    $form_state['redirect'] = 'admin/content/ntuts_question/question';
  }
}

/**
 * Theme the question admin form.
 *
 * @param $form
 *   An associative array containing the structure of the form.
 * @ingroup themeable
 */
function theme_ntuts_question_list_question($form) {
  $output = drupal_render($form['options']);
  if (isset($form['node_title']) && is_array($form['node_title'])) {
    foreach (element_children($form['node_title']) as $key) {
      $row = array();
      $row[] = drupal_render($form['questions'][$key]);
      $row[] = drupal_render($form['username'][$key]);
      $row[] = drupal_render($form['node_title'][$key]);
      $row[] = drupal_render($form['timestamp'][$key]);
      $row[] = drupal_render($form['status'][$key]);
      $row[] = drupal_render($form['operations'][$key]);
      $rows[] = $row;
    }
  }
  else {
    $rows[] = array(array('data' => t('No questions available.'), 'colspan' => '6'));
  }

  $output .= theme('table', $form['header']['#value'], $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}


/**
 * Form builder; generate a question editing form.
 *
 * @param $qid
 *   ID of the question to be edited.
 * @ingroup forms
 */
function ntuts_question_edit_question($qid) {
  $question = db_fetch_array(db_query('SELECT q.*, u.uid, u.name, u.data FROM {ntuts_question} q INNER JOIN {users} u ON q.uid = u.uid WHERE q.qid = %d', $qid));
  return question_form_box((array)$question);
}

/**
 * Theme the question form box.
 *
 * @param $edit
 *   The form structure.
 * @param $title
 *   The form title.
 */
function question_form_box($edit, $title = NULL) {
  return theme('box', $title, drupal_get_form('question_form', $edit, $title));
}
/**
 * Generate the basic question form, for appending to a node or display on a separate page.
 *
 * @param $title
 *   Not used.
 * @ingroup forms
 * @see question_form_submit()
 */
function question_form(&$form_state, $edit, $title = NULL) {
  global $user;
  $node = node_load($edit['nid']);
  $form['information'] = array(
        '#type' => 'fieldset',
        '#title' => t('Information'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#weight' => -2,
      );
  $form['information']['author'] = array(
          '#type' => 'textfield',
          '#title' => t('Authored by'),
          '#size' => 30,
          '#maxlength' => 60,
          '#disabled' => true,
          '#default_value' => $edit['name'],
          '#weight' => -1,
        );
    $form['information']['node-title'] = array(
          '#type' => 'textfield',
          '#title' => t('Node Title'),
          '#size' => 100,
          '#maxlength' => 100,
          '#disabled' => true,
          '#default_value' => $node->title,
          '#weight' => -1,
        );
  if (!empty($edit['question'])) {
    $default = $edit['question'];
  }
  else {
    $default = '';
  }

  $form['question']['question'] = array(
    '#type' => 'textarea',
    '#title' => t('Question'),
    '#rows' => 15,
    '#default_value' => $default,
    '#required' => TRUE,
  );
  $options = array(    
      '0' => 'Unpublish',
      '1' => 'Publish',
  );
  $form['question']['status'] = array(
    '#type' => 'select',
    '#title' => t('Status'),
    '#options' => $options,
    '#default_value' => $edit['status'],
  );
  $form['qid'] = array('#type' => 'value', '#value' => !empty($edit['qid']) ? $edit['qid'] : NULL);
  $form['nid'] = array('#type' => 'value', '#value' => $edit['nid']);
  $form['uid'] = array('#type' => 'value', '#value' => !empty($edit['uid']) ? $edit['uid'] : 0);

  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
  return $form;
}

/**
 * Process question form submissions; prepare the question, store it, and set a redirection target.
 */
function question_form_submit($form, &$form_state) {
  if (question_save($form_state['values'])) {
    drupal_set_message(t('The question was updated successful.'));
    $form_state['redirect'] = 'admin/content/ntuts_question/question';
    return;
  }
}



/**
 * Form builder; Builds the answer overview form for the admin.
 *
 * @return
 *   The form structure.
 * @ingroup forms
 * @see ntuts_question_list_answer_validate()
 * @see ntuts_question_list_answer_submit()
 * @see theme_ntuts_question_list_answer()
 */
function ntuts_question_list_answer() {
  // build an 'Update options' form
  $form['options'] = array(
    '#type' => 'fieldset', '#title' => t('Update options'),
    '#prefix' => '<div class="container-inline">', '#suffix' => '</div>'
  );
  $options = array(
      'unpublish' => 'Unpublish the selected answers',
      'publish' => 'Publish the selected answers',
      'delete' => 'Delete the selected answers',
  );
  $form['options']['operation'] = array('#type' => 'select', '#options' => $options, '#default_value' => 'unpublish');
  $form['options']['submit'] = array('#type' => 'submit', '#value' => t('Update'));

  // load the questions that we want to display
  $form['header'] = array('#type' => 'value', '#value' => array(
    theme('table_select_header_cell'),
    array('data' => t('Author'), 'field' => 'name'),
    array('data' => t('Question')),
    array('data' => t('Time'), 'field' => 'timestamp', 'sort' => 'desc'),
    array('data' => t('Status'), 'field' => 'status'),
    array('data' => t('Vote'), 'field' => 'answer_vote'),
    array('data' => t('Operations'))
  ));
  $result = pager_query('SELECT a.timestamp, a.answer_vote, a.status, a.aid, u.name, u.data, a.qid, q.question FROM {ntuts_answer} a INNER JOIN {users} u ON u.uid = a.uid INNER JOIN {ntuts_question} q ON q.qid = a.qid '. tablesort_sql($form['header']['#value']), 50, 0, NULL);

  // build a table listing the appropriate questions
  $destination = drupal_get_destination();
  while ($answer = db_fetch_object($result)) {

    $answer->question = drupal_substr($answer->question, 0, 28);
    if ( drupal_strlen($answer->question) == '28' ) { $answer->question .= "..."; }
    $answer->question = check_plain($answer->question);

    $answers[$answer->qid] = '';
    $form['username'][$answer->aid] = array('#value' => theme('username', $answer)); 
    $form['question'][$answer->aid] = array('#value' => l($answer->question, 'admin/content/ntuts_question/question/edit/'. $answer->qid));
    $form['timestamp'][$answer->aid] = array('#value' => format_date($answer->timestamp, 'small'));
    $form['status'][$answer->aid] = array('#value' => $answer->status ? t('Published') : t('Not Published'));
    $form['answer_vote'][$answer->aid] = array('#value' => t($answer->answer_vote));
    $form['operations'][$answer->aid] = array('#value' => l(t('edit'), 'admin/content/ntuts_question/answer/edit/'. $answer->aid, array('query' => $destination)));
  }
  $form['answers'] = array('#type' => 'checkboxes', '#options' => isset($answers) ? $answers: array());
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  return $form;
}

/**
 * Validate ntuts_question_list_answer form submissions.
 *
 * We can't execute any 'Update options' if no answers were selected.
 */
function ntuts_question_list_answer_validate($form, &$form_state) {
  $form_state['values']['answers'] = array_diff($form_state['values']['answers'], array(0));
  if (count($form_state['values']['answers']) == 0) {
    form_set_error('', t('Please select one or more answers to perform the update on.'));
  }
}

/**
 * Process ntuts_question_list_answer form submissions.
 *
 * Execute the chosen 'Update option' on the selected answers, such as
 * publishing, unpublishing or deleting.
 */
function ntuts_question_list_answer_submit($form, &$form_state) {
  $operations = array(
      'unpublish' => 'Unpublish the selected questions',
      'publish' => 'Publish the selected questions',
      'delete' => 'Delete the selected questions',
  );
  if (!empty($operations[$form_state['values']['operation']])) {
    $query = '';
    switch ($form_state['values']['operation']) {
      case 'unpublish':
        $query = 'UPDATE {ntuts_answer} SET status = 0 WHERE aid = %d';
        break;
      case 'publish':
        $query = 'UPDATE {ntuts_answer} SET status = 1 WHERE aid = %d';
        break;
      case 'delete':
        $query = 'DELETE FROM {ntuts_answer} WHERE aid = %d';
        break;
      default:
        break;
    }
    // extract the appropriate database query operation
    if(!empty($query)) {

      foreach ($form_state['values']['answers'] as $aid => $value) {
        if ($value) {
          // perform the update action, then refresh node statistics
          db_query($query, $aid);
        }
      }
      drupal_set_message(t('The update has been performed.'));
    }
    $form_state['redirect'] = 'admin/content/ntuts_question/answer';
  }
}

/**
 * Theme the question admin form.
 *
 * @param $form
 *   An associative array containing the structure of the form.
 * @ingroup themeable
 */
function theme_ntuts_question_list_answer($form) {
  $output = drupal_render($form['options']);
  if (isset($form['username']) && is_array($form['username'])) {
    foreach (element_children($form['username']) as $key) {
      $row = array();
      $row[] = drupal_render($form['answers'][$key]);
      $row[] = drupal_render($form['username'][$key]);
      $row[] = drupal_render($form['question'][$key]);
      $row[] = drupal_render($form['timestamp'][$key]);
      $row[] = drupal_render($form['status'][$key]);
      $row[] = drupal_render($form['answer_vote'][$key]);
      $row[] = drupal_render($form['operations'][$key]);
      $rows[] = $row;
    }
  }
  else {
    $rows[] = array(array('data' => t('No questions available.'), 'colspan' => '7'));
  }

  $output .= theme('table', $form['header']['#value'], $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}


/**
 * Form builder; generate a answer editing form.
 *
 * @param $qid
 *   ID of the answer to be edited.
 * @ingroup forms
 */
function ntuts_question_edit_answer($aid) {
  $answer = db_fetch_array(db_query('SELECT a.*, u.uid, u.name, q.question FROM {ntuts_answer} a INNER JOIN {users} u ON a.uid = u.uid INNER JOIN {ntuts_question} q ON a.qid = q.qid WHERE a.aid = %d', $aid));
  return answer_form_box((array)$answer);
}

/**
 * Theme the answer form box.
 *
 * @param $edit
 *   The form structure.
 * @param $title
 *   The form title.
 */
function answer_form_box($edit, $title = NULL) {
  return theme('box', $title, drupal_get_form('answer_form', $edit, $title));
}
/**
 * Generate the basic answer form, for appending to a node or display on a separate page.
 *
 * @param $title
 *   Not used.
 * @ingroup forms
 * @see answer_form_submit()
 */
function answer_form(&$form_state, $edit, $title = NULL) {
  $form['information'] = array(
        '#type' => 'fieldset',
        '#title' => t('Information'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#weight' => -2,
      );
  $form['information']['author'] = array(
          '#type' => 'textfield',
          '#title' => t('Authored by'),
          '#size' => 30,
          '#maxlength' => 60,
          '#disabled' => true,
          '#default_value' => $edit['name'],
          '#weight' => -1,
        );
    $form['information']['node-title'] = array(
          '#type' => 'textfield',
          '#title' => t('Question'),
          '#size' => 100,
          '#maxlength' => 100,
          '#disabled' => true,
          '#default_value' => $edit['question'],
          '#weight' => -2,
        );
  if (!empty($edit['answer'])) {
    $default = $edit['answer'];
  }
  else {
    $default = '';
  }

  $form['answer']['answer'] = array(
    '#type' => 'textarea',
    '#title' => t('answer'),
    '#rows' => 15,
    '#default_value' => $default,
    '#required' => TRUE,
  );
  $options = array(
      '0' => 'Unpublish',
      '1' => 'Publish',
  );
  $form['answer']['status'] = array(
    '#type' => 'select',
    '#title' => t('Status'),
    '#options' => $options,
    '#default_value' => $edit['status'],
  );
  $form['aid'] = array('#type' => 'value', '#value' => !empty($edit['aid']) ? $edit['aid'] : NULL);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
  return $form;
}

/**
 * Process question form submissions; prepare the question, store it, and set a redirection target.
 */
function answer_form_submit($form, &$form_state) {
  if (answer_save($form_state['values'])) {
    drupal_set_message(t('The answer was updated successful.'));
    $form_state['redirect'] = 'admin/content/ntuts_question/answer';
    return;
  }
}
